package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.auth.utils.RsaUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户登录
     * @param username  用户名
     * @param password  用户密码
     * @param response  HttpResqonse
     */
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //校验用户名和密码
            UserDTO ud = userClient.queryByUsernameAndPassword(username, password);
            //生成jwt
            UserInfo userInfo = new UserInfo(ud.getId(),ud.getUsername(),"guest");

            String token = JwtUtils.generateTokenExpireInMinutes(
                                userInfo,
                                jwtProperties.getPrivateKey(),
                                jwtProperties.getUser().getExpire()
                            );
            //存入cookie
            CookieUtils.newCookieBuilder()
                    .name(jwtProperties.getUser().getCookieName())     //cookie名称
                    .value(token)   //生成的token
                    .domain(jwtProperties.getUser().getCookieDomain())   //cookie的域
                    .httpOnly(true) //避免XSS攻击
                    .response(response) //响应对象, 把cookie写入浏览器
                    .build();
        } catch (Exception e){
            log.error("【授权中心】用户登录失败: {}",e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

    /**
     * 验证token, 并返回token中的用户信息
     * @param request   cookie所在请求
     * @param response  cookie所在响应
     * @return  返回token中载荷对象UserInfo
     */
    public UserInfo verifyUser(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            //从cookies中获取token
            String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
            //解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);

            //黑名单token校验
            String key = payload.getId();
            Boolean bool = stringRedisTemplate.hasKey(key);
            if (bool != null && bool){
                //黑名单存在
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }

            //判断是否更新token(token失效时间延时)
            Date expiration = payload.getExpiration();
            DateTime dateTime = new DateTime(expiration).minusMinutes(jwtProperties.getUser().getRefreshTime());
            if (dateTime.isBeforeNow()){   //token过期时间前10分钟(时间点) 在当前时间前, 说明满足小于10分钟(要延时)
                String newToken = JwtUtils.generateTokenExpireInMinutes(payload.getUserInfo(), jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());
                //重新导入浏览器的Cookies
                CookieUtils.newCookieBuilder()
                        .name(jwtProperties.getUser().getCookieName())     //cookie名称
                        .value(newToken)   //生成的token
                        .domain(jwtProperties.getUser().getCookieDomain())   //cookie的域
                        .httpOnly(true) //避免XSS攻击
                        .response(response) //响应对象, 把cookie写入浏览器
                        .build();
            }

            //返回用户信息
            return payload.getUserInfo();
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    /**
     * 用户退出
     * @param request   请求(获取cookie)
     * @param response  响应(删除cookie)
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取请求中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
        //解析token
        Payload<Object> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e){
            //如果解析失败说明token已经过期. 无需存入redis黑名单中
            return;
        }
        //获取token剩余时间
        long expTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        //存入redis中: 有效期大于3s才存
        if (expTime > 3000){
            String key = payload.getId();
            stringRedisTemplate.opsForValue().set(key,"1",expTime, TimeUnit.MILLISECONDS);
        }

        //删除浏览器中的cookie
        CookieUtils.deleteCookie(
                jwtProperties.getUser().getCookieName(),
                jwtProperties.getUser().getCookieDomain(),
                response
        );
    }

    /**
     * 微服务的授权功能
     * @param id       服务id
     * @param secret   服务密码
     * @return         给服务签发的token
     */
    public String authorize(Long id, String secret) {
        //1. 校验微服务的id和密码
        ApplicationInfo app = applicationInfoMapper.selectByPrimaryKey(id);
        //校验是否存在
        if (app == null){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //校验密码
        if (!passwordEncoder.matches(secret,app.getSecret())){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }

        //2. 校验当前微服务具有哪些权限
        List<Long> targetIdList = applicationInfoMapper.queryTargetIdList(id);

        //3. 把对象封装到token的载荷对象中
        AppInfo appInfo = new AppInfo();
        appInfo.setId(id);
        appInfo.setServiceName(app.getServiceName());
        appInfo.setTargetList(targetIdList);

        //4. 生成token并返回
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProperties.getPrivateKey(),jwtProperties.getApp().getExpire());
        return token;
    }
}
